package sw.EngAdroid;

import java.util.*;
import java.util.Map.Entry;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

import netcode.client.Client;
import netcode.helper.ClientMessageListener;
import netcode.helper.NetcodeHelper;

public class LobbySelectActivity extends Activity implements
		ClientMessageListener {
	private Button createGameButton;
	private Button refreshButton;
	private Button joinGameButton;
	private Game game;
	private Client client;
	private String name;
	private boolean serverLobbyInfoReceived = false;
	private boolean gameLobbyInfoReceived = false;
	private boolean questionReceived = false;
	private boolean bettingOddsReceived = false;
	private boolean roundResultsReceived = false;
	private boolean endOfGameReceived = false;
	private boolean small = false;
	private Game selectedGame;
	private int gameID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		if (dm.widthPixels < 1000) {
			setContentView(R.layout.lobby_select_screen_small);
			small = true;
		} else
			setContentView(R.layout.lobby_select_screen);

		game = new Game();
		name = "test";
		try {
			client = new Client(NetcodeHelper.SERVER_ADDRESS,
					NetcodeHelper.SERVER_PORT, name, game);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		client.setListener(this);

		client.start();
		client.sendConnectionRequest();
		initControls();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void initControls() {
		refreshLobby();
		createGameButton = (Button) findViewById(R.id.createGameButton);

		createGameButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				// Actions for when Create Game is selected
				Intent intent = new Intent(getApplication(),
						LobbyCreateGameActivity.class);
				startActivity(intent);

			}
		});

		joinGameButton = (Button) findViewById(R.id.joinGameButton);
		joinGameButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if (gameID != 0){
					
//					switch(selectedGame.getPlayers().size()){
//					case 4:intent = new Intent(getApplication(),
//							NetFourPlayerActivity.class);break;
//					case 5:intent = new Intent(getApplication(),
//							NetFivePlayerActivity.class);break;
//					case 6:intent = new Intent(getApplication(),
//							NetSixPlayerActivity.class);break;
//					default:intent = new Intent(getApplication(),
//							NetThreePlayerActivity.class);break;
//					}
				

				
				//Create alert
    			AlertDialog.Builder userName = new AlertDialog.Builder(v.getContext());

    			//Set title and message
    			userName.setTitle("Player Name");
    			userName.setMessage("Enter Your name");
    			
    			//Set up text field
    			final EditText inputField = new EditText(v.getContext());
    			userName.setView(inputField);
    			
    			final View temp = v;
    			
    			//Set up a confirm button in alert
    			userName.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    				//Packages the user Name into a bundle and passes it into the gameActivity
    				public void onClick(DialogInterface dialog, int whichButton) {
    					
    					String playerName = inputField.getText().toString().replaceAll("\n", "");
    					System.out.println(playerName);
    					client.sendDisconnect();
    					Bundle gameInfo = new Bundle();
    					gameInfo.putBoolean("isHost", false);
    					gameInfo.putInt("gameID",gameID);
    					gameInfo.putString("playerName", playerName);
    					Intent intent = new Intent(getApplication(),NetPlay.class);
    					intent.putExtras(gameInfo);
    					startActivity(intent);
      				}
    			});
    			
    			//Set up cancel button that exits alert and does nothing
    			userName.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    			  public void onClick(DialogInterface dialog, int whichButton) {
    			  }
    			});
    			
    			//Show alert
    			userName.show();
				}
			}
		});

		refreshButton = (Button) findViewById(R.id.refreshButton);

		refreshButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				// Actions for when Refresh is selected
				refreshLobby();

			}
		});

		// Initial population of lobby

	}

	public void onMessageReceived(byte packetCode) {
		System.out.println("onMessageReceived() entered with code: "
				+ packetCode);
		switch (packetCode) {
		case NetcodeHelper.SERVER_LOBBY_INFO_RESPONSE:
			serverLobbyInfoReceived = true;
			break;
		case NetcodeHelper.GAME_LOBBY_INFO:
			gameLobbyInfoReceived = true;
			break;
		case NetcodeHelper.QUESTION:
			questionReceived = true;
			break;
		case NetcodeHelper.BETTING_ODDS:
			bettingOddsReceived = true;
			break;
		case NetcodeHelper.ROUND_RESULTS:
			roundResultsReceived = true;
			break;
		case NetcodeHelper.GAME_RESULTS:
			endOfGameReceived = true;
			break;
		}

	}

	// Refreshes list of all games in lobby
	public void refreshLobby() {
		client.sendServerLobbyInfoRequest();
		Object[] temp = client.getLobby().getAllGames().values().toArray();
		Game[] allGameValues = new Game[temp.length];
		for (int i = 0; i < temp.length; i++) {
			allGameValues[i] = (Game) temp[i];
		}
		// Game currentLobbyGame; //Current game in iteration, used for
		// populating array used by spinner
		// String [] items=new String[allGameValues.size()]; //Each string in
		// array represents a lobby game
		// int i = 0;
		// for(Iterator<Game> lobbyIterator = allGameValues.iterator();
		// lobbyIterator.hasNext(); i++)
		// {
		// currentLobbyGame = lobbyIterator.next();
		// items[i] = currentLobbyGame.getName();
		// }

		ArrayAdapter ad = new ArrayAdapter(this,
				android.R.layout.simple_spinner_item, allGameValues);
		ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		final Spinner spin = (Spinner) findViewById(R.id.Spinner);
		spin.setAdapter(ad);
		spin.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				Iterator<Entry<Integer, Game>> it = client.getLobby().getAllGames().entrySet().iterator();
				String name = ((Game)spin.getItemAtPosition(arg2)).getName();
				while(it.hasNext()){
					Entry<Integer,Game> next = it.next();
					if(next.getValue().getName().equals(name)){
						gameID = next.getKey();
					}
				}
				//selectedGame = (Game) spin.getItemAtPosition(arg2);

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				//selectedGame = null;
				gameID = 0;
			}

		});

	}
	
	public void sleepyTime() {
		try {
			Thread.sleep(NetcodeHelper.MILLISECONDS_BETWEEN_SENDING_MESSAGE);
		} catch (Exception e) {
			System.err.println(e);
		}
	}
}
